<template>
  <div class="wapper">
    <el-container style="100%">
      <el-main style="background:#fff;">
        <div class="table-wrap" v-show="listShow">
          <div class="handle-box3">
            <el-form :inline="true" ref="form" :model="searchForm" class="demo-form-inline">
              <div class="uers-left">
                <el-form-item label="搜索：">
                  <el-input v-model="searchForm.name" placeholder="名称"></el-input>
                </el-form-item>
                <el-form-item label>
                  <el-input v-model="searchForm.phone" placeholder="手机"></el-input>
                </el-form-item>
                <el-form-item label>
                  <el-input v-model="searchForm.code" placeholder="码值"></el-input>
                </el-form-item>
                <el-form-item label>
                  <el-select
                    placeholder="注册类型："
                    clearable
                    v-model="searchForm.type"
                    class="el-input-position"
                  >
                    <el-option  v-for="(item,index) in types" :key="index" :label="item.name" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label>
                  <el-select
                    placeholder="注册通道："
                    clearable
                    v-model="searchForm.registerId"
                    class="el-input-position"
                  >
                    <el-option  v-for="(item,index) in registers" :key="index" :label="item.name" :value="item.registerId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="">
                  <el-date-picker v-model="searchForm.startDate" type="datetime" placeholder="开始日期"></el-date-picker>
                </el-form-item>
                <el-form-item label="">
                  <el-date-picker v-model="searchForm.endDate" type="datetime" placeholder="开始日期"></el-date-picker>
                </el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchSubmit()">搜索</el-button>
                <el-button type="primary" icon="el-icon-export" @click="exportExcel()">导出</el-button>
              </div>
              <div class="uers-right">
                <span class="btn-r">
                  <el-button type="primary" plain icon="el-icon-plus" @click="addSubmit">新增</el-button>
                </span>
                <el-popover placement="bottom" title="批量导入" width="220" trigger="click">
                  <div>
                    <el-upload
                      class="upload-demo"
                      :action="action"
                      :auto-upload="false"
                      :on-change="uploadChange"
                      accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                      >
                      <el-button size="small" type="primary">选择导入模板</el-button>
                    </el-upload>
                    <el-button type="success" @click="download" plain icon="el-icon-download" class="down-template">下载模板</el-button>
                  </div>
                  <p class="import-text">只能选择 .xls .xlsx 文件</p>
                  <div>
                    <el-button type="success" @click="importData">开始导入</el-button>
                  </div>
                  <el-button type="primary" plain icon="el-icon-upload2" slot="reference">导入人员</el-button>
                </el-popover>&nbsp;&nbsp;&nbsp;
              </div> 
            </el-form> 
          </div>
          <div class="tabbox">
          <el-table
            :data="dataList"
            height="100%"
            border
            class="tabbox"
            ref="multipleTable"
            :header-cell-style="{background:'#f2f6fc',color:'#606266'}"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="name"  width="120" label="姓名" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="phone"  width="120" label="手机" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.phone}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="email" width="150" label="邮箱" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.email}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="idcard" width="150" label="身份证" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.idcard}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="company" label="公司" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.company}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="position" width="120" label="职位" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.position}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="verify" width="100"  label="审核" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.verify==1?'已审核':'未审核'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="disabled" width="100" label="状态" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.disabled==1?'禁用':'启用'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="isSign" width="100" label="签到" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.isSign==1?'已签到':'未签到'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" width="100" label="码值" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.code}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createDate"  width="160" label="创建时间" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.createDate}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
                <el-button type="text" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table></div>
          <div class="fb"><el-pagination
            class="pag"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
          ></el-pagination></div>
        </div>
        <DeleteDialog
          :delVisible="delVisible"
          @deleteData="deleteData"
          @handleCloseVisible="handleCloseVisible"
        ></DeleteDialog>
        <EditExhibitorsPersonal :editShow="editShow" :editData="editData" @backFunStu="getFunStu"></EditExhibitorsPersonal>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import EditExhibitorsPersonal from "../../components/major/EditExhibitorsPersonal";
import DeleteDialog from "../../components/public/DeleteConfim";

var types=[
    {name:"全部类型",value:"0"},
    {name:"组委会",value:"1"},
    {name:"展商",value:"2"},
    {name:"展团/代表团",value:"3"},
    {name:"观众" ,value:"4"},
    {name:"媒体", value:"5"},
    {name:"嘉宾" ,value:"6"},
    {name:"搭建商" ,value:"7"},
    {name:"服务商" ,value:"8"},
    {name:"撤展人员" ,value:"9"},
    {name:"兼职/志愿者/外协" ,value:"10"},
    {name:"会议/论坛/活动" ,value:"11"},
    {name:"其他" ,value:"12"}
  ];

export default {
  data() {
    return {
      total: 0, //总条数
      currentPage: 1, //初始页
      pagesize: 10, // 每页的数据
      searchForm: {
        name: "",
        phone: "",
        type: "0",
        code:"",
        endDate:new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1),
        startDate:new Date(new Date(new Date().toLocaleDateString()).getTime()-(new Date(new Date().toLocaleDateString()).getTime() - new Date(new Date().getFullYear().toString()))),
        registerId:"",
      },
      types:types,
      registers:[],
      action:localStorage.getItem("url"),
      editData: {},
      listShow: true,
      editShow: false,
      delVisible: false,
      dataList: [],
      multipleSelection: [],
      productId: localStorage.getItem("project_Id"),
      personal_Id: ""
    };
  },
  created() {
    this.getData();
    this.loadData();
  },
  methods: {
    loadData(){
      this.$axios.get('/Register/Project/'+this.productId)
        .then(res =>{
          if (res.data.hasError == false) {
              this.registers=[...res.data.data]; 
          }else{
            console.log(res.data.message);
          }
        }).catch(function(){
      })
    },
    exportExcel(){
      var search = {
        name: this.searchForm.name,
        pageIndex: this.currentPage - 1,
        pageSize: this.pagesize,
        phone: this.searchForm.phone,
        code: this.searchForm.code,
        exhibitorId: 0,
        startDate: this.searchForm.startDate,
        endDate: this.searchForm.endDate,
        projectId: this.productId,
        type: this.searchForm.type,
        registerId:this.searchForm.registerId==""?0:parseInt(this.searchForm.registerId)
      };
      this.$axios.post({
      url:`/Personal/Export`,
      method:`post`,
      responseType: 'blob',
      data:search
      }).then(res => {
      let blob = res.data
      let reader = new FileReader()
      reader.readAsDataURL(blob)
      reader.onload = (e) => {
        let a = document.createElement('a')
        a.download = `fileName.xlsx`
        a.href = e.target.result
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
      })
      /*this.$axios.post("/Personal/Export", search,{responseType: "blob"}).then(res => {
          const blob = new Blob([res.data], {
                type: "application/vnd.ms-excel"
            });
            let fileName = "人.xls";
            if ("download" in document.createElement("a")) {
                const elink = document.createElement("a");
                elink.download = fileName;
                elink.style.display = "none";
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
            } else {
                navigator.msSaveBlob(blob, fileName);
            }
      });*/
    },
    uploadChange(file, fileList){
      let inputDOM = this.$refs.inputer; // 通过DOM取文件数据

      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;

      var reader = new FileReader(); //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function(f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function(e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64"
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          } // outdata就是你想要的东西 excel导入的数据
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); // excel 数据再处理
          let ar=[];
          outdata.map(v => {
            let obj = {};
            obj.name = v.姓名;
            obj.sex = v.性别;
            obj.phone = v.手机号;
            obj.idCard = v.身份证;
            obj.email = v.邮箱;
            obj.width = v.宽度;
            obj.avatar = v.已审核;
            obj.company = v.公司;
            obj.position = v.职务;
            obj.area = v.地区;
            obj.address = v.地址;
            obj.code = v.码值;
            obj.booth = v.展位号;
            obj.openId = v.来源;
            ar.push(obj);
          });
          localStorage.setItem('attr',JSON.stringify(ar))
          };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    importData(){ 
        if(this.searchForm.registerId!=''){
          this.attr=  JSON.parse(localStorage.getItem('attr'))
          if(this.attr&&this.attr.length>0){            
            const loading =this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              });  
              this.$axios.patch('/Personal/'+this.searchForm.registerId,this.attr)
                .then(res =>{
                  if (res.data.hasError == false) {
                    loading.close();
                    this.searchSubmit();
                    localStorage.setItem('attr',null);
                    this.$message.success(res.data.message);
                  }else{
                    this.$message.error(res.data.message);
                    loading.close();
                  }
                }).catch(function(){
                  loading.close();
                })
            }else{
              this.$message.error("没有可上传的数据");
            }
        }else{
          this.$message.error("请选择注册通道");
        }
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getData();
    },
    addSubmit() {
      this.listShow = false;
      this.editShow = true;
    },
    searchSubmit() {
      this.currentPage=1;
      this.getData();
    },
    handleDelete(index, row) {
      this.personal_Id = row.personalId;
      this.delVisible = true;
    },
    handleCloseVisible() {
      this.personal_Id = "";
      this.delVisible = false;
    },
    download(){
      var url=localStorage.getItem('url');
      if(url.lastIndexOf('/api')==url.indexOf('/api')){
        window.open(url.replace('/api','/')+'/upload/用户模板.xlsx')
      }else{
        window.open(url.substring(0,url.lastIndexOf('/api'))+'/upload/用户模板.xlsx')
      }
    },
    deleteData() {
      this.$axios.delete(`/Personal/${this.personal_Id}`).then(res => {
          this.$message.success("删除成功！");
          this.delVisible = false;
          this.getData();
      });
    },
    // 获取数据
    getData() {
      var search = {
        name: this.searchForm.name,
        pageIndex: this.currentPage - 1,
        pageSize: this.pagesize,
        phone: this.searchForm.phone,
        code: this.searchForm.code,
        exhibitorId: 0,
        startDate: this.searchForm.startDate,
        endDate: this.searchForm.endDate,
        projectId: this.productId,
        type: this.searchForm.type,
        registerId:this.searchForm.registerId==""?0:parseInt(this.searchForm.registerId)
      };
      this.$axios.post("/Personal/Search", search).then(res => {
        if (res.data.hasError == false) {
          this.dataList = [...res.data.data];
          this.total = res.data.total;;
        }
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleEdit(index, row) {
      this.editData = row;
      this.listShow = false;
      this.editShow = true;
    },
    getFunStu() {
      this.listShow = true;
      this.editShow = false;
      this.getData();
    }
  },
  components: {
    EditExhibitorsPersonal,
    DeleteDialog
  }
};
</script>
<style lang="scss" scope>
.pag {
  position: absolute;
  bottom: 0;
}

.table-wrap {
  margin-left: 10px;
  height: 100%;
}
.el-main {
  border-radius: 5px;
  position: relative;
}
.uers-left {
  float: left;
}
.uers-right {
  float: right;
}
.uers-import {
  margin-right: 30px;
  float: right;
  width: 240px;
}
.upload-excel {
  float: left;
}
.import-bnt {
  float: right;
}
.el-upload {
  height: 32px !important;
  line-height: 32px !important;
  width: 120px !important;
}
.el-upload--text {
  border: 0;
}
.file-up {
  width: 100px;
  position: absolute;
  height: 32px;
  opacity: 0;
}
.import-text {
  margin: 15px 0;
}
.el-upload--text{
  width: 110px;
  height: 32px;
  line-height: 32px;
  border: 0;
}
.down-template{
  position: absolute;
  top: 40px;
  right: 10px;
}

</style>